const Subscription = require('egg').Subscription;

class TaskInfoqWeekly extends Subscription {
  // 通过 schedule 属性来设置定时任务的执行间隔等配置
  static get schedule() {
    return {
      cron: '0 10 6 * * ?',
      type: 'worker',
      env: ['pachong']
    };
  }

  // subscribe 是真正定时任务执行时被运行的函数
  async subscribe() {
    let topics = await this.ctx.service.crawlerSvc.infoqWeekly();

    for (let i = 0; i < topics.length; i++) {
      let topic = topics[i];
      try {
        let result = await this.ctx.model.Topic.create(topic);
      } catch (e) {
        let now = Date.now();
        await this.ctx.model.Topic.updateOne({title: topic.title, author_name: 'InfoQ', boards: {$ne: '技术周刊'}},
          {
            $addToSet: {boards: '技术周刊', tags: '技术周刊'},
            $set: {createdAt: now, updatedAt: now, last_reply_at: now}
          }
        )
      }
    }
  }
}

module.exports = TaskInfoqWeekly;
